<?php
namespace app\adm\controller;
use think\Controller;
use think\Db;
use think\Request;

/**
 * 登陆注册
 */
class Sign extends Controller{
     public function __construct(Request $request){
        parent::__construct();
         //全局变量定义
         $this -> assign('app_name', config('app_name'));
     }
    /*
     * 后台登录
    */
    public function login(Request $request){
        if(!$request->isAJax()){
            return $this->fetch($request->action(),['title'=>'登录']);
        }else{
            $data = Request::instance()->post();

            if(!captcha_check($data['code'])){
                $this->error('验证码输入有误');
            }
            
            $find = Db::name('auth_user')->where(['loginName'=>$data['username']])->find();
            if(!$find){
                $this->error('用户名不存在');
            }else if($find['loginPassword'] !== strtolower(md5(md5($data['password'])))){
                $this->error('密码错误');
            }
            Db::name('auth_user')->where(['uid'=>$find['uid']])->setField('last_login_date',date('Y-m-d H:i:s'));

            $this->setLoginSession($find);
            adminOperationRecord('登录后台');
            $this->success('',url('index/index'));
        }
    }

    protected function setLoginSession($user){
        session('uid',$user['uid']);
        session('loginName',$user['loginName']);
        session('head_img',$user['head_img']);
        session('group_id',$user['group_id']);
        session('admin',$user);
        return true;
    }

    public function logout(){
        session(null);
        $this->redirect(url('login'));
    }
}
